import 'dart:convert';

import 'package:azlistview/azlistview.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gourmet/color/hex.dart';
import 'package:gourmet/extensions/fun.dart';
import 'package:gourmet/model/city.dart';
import 'package:gourmet/utils/colors.dart';
import 'package:gourmet/utils/styles.dart';
import 'package:gourmet/utils/tools.dart';
import 'package:lpinyin/lpinyin.dart';

class ReceiveAddressCityController extends GetxController {
  RxList<CityModel> cityList = RxList([]);
  double susItemHeight = 36;

  String imgFavorite = ToolsUtils.getImgPath('ic_favorite');

  @override
  void onInit() {
    loadData();
    super.onInit();
  }

  void loadData() async {
    ///加载城市列表
    rootBundle.loadString('assets/data/china.json').then((value) {
      cityList.clear();
      Map countyMap = json.decode(value);
      List list = countyMap['china'];
      for (var v in list) {
        cityList.add(CityModel.fromJson(v));
      }
      _handleList(cityList);
    });
  }

  void _handleList(List<CityModel> list) {
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }
    SuspensionUtil.sortListBySuspensionTag(list);

    SuspensionUtil.setShowSuspensionStatus(cityList);

    cityList.insert(
      0,
      CityModel(name: 'header', tagIndex: imgFavorite),
    );
  }
}

class ReceiveAddressCityPage extends GetView<ReceiveAddressCityController> {
  const ReceiveAddressCityPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        systemOverlayStyle: SystemUiOverlayStyle.dark,
        leading: IconButton(
          onPressed: Get.back,
          icon: Icon(
            CupertinoIcons.chevron_back,
            size: 20.sp,
            color: HexColor(ColorsUtils.color0000),
          ),
        ),
        title: Text(
          '选择城市',
          style: StylesUtils.customTextStyle(
            fontSize: StylesUtils.fontSize16,
            color: ColorsUtils.color0000,
            fontWeight: FontWeight.w700,
          ),
        ),
        centerTitle: true,
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(40),
          child: Container(
            height: 40,
            alignment: Alignment.center,
            child: TextField(
              cursorHeight: 20,
              cursorWidth: 3,
              cursorRadius: const Radius.circular(2),
              cursorColor: HexColor(ColorsUtils.colorFf64),
              style: StylesUtils.customTextStyle(
                fontSize: StylesUtils.fontSize15,
                color: ColorsUtils.color0000,
              ),
              textAlign: TextAlign.left,
              textAlignVertical: TextAlignVertical.center,
              textDirection: TextDirection.ltr,
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                hintText: '请输入城市名称',
                hintStyle: StylesUtils.customTextStyle(
                  fontSize: StylesUtils.fontSize15,
                  color: ColorsUtils.color9999,
                ),
                filled: true,
                fillColor: HexColor(ColorsUtils.colorF7f7),
                isDense: true,
                isCollapsed: true,
                prefixIconConstraints:
                    const BoxConstraints.expand(height: 35, width: 40),
                prefixIcon: Container(
                  alignment: Alignment.center,
                  child: Icon(
                    CupertinoIcons.search,
                    size: 20,
                    color: HexColor(ColorsUtils.color9999),
                  ),
                ),
                contentPadding:
                    const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(13),
                  borderSide: BorderSide.none,
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(13),
                  borderSide: BorderSide.none,
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(13),
                  borderSide: BorderSide.none,
                ),
                constraints:
                    const BoxConstraints.expand(width: 330, height: 35),
              ),
              onChanged: (String keyword) {}.useDebounce((String keyword) {}),
            ),
          ),
        ),
      ),
      body: Obx(
        () => AzListView(
          data: controller.cityList,
          itemCount: controller.cityList.length,
          itemBuilder: (BuildContext context, int index) {
            if (index == 0) return _buildHeader();
            CityModel model = controller.cityList[index];
            return getListItem(context, model, susHeight: 36);
          },
          susItemHeight: 36,
          susItemBuilder: (BuildContext context, int index) {
            CityModel model = controller.cityList[index];
            String tag = model.getSuspensionTag();
            if (controller.imgFavorite == tag) {
              return Container();
            }
            return getSusItem(context, tag, susHeight: 36);
          },
          indexBarData: SuspensionUtil.getTagIndexList(controller.cityList),
          indexBarOptions: IndexBarOptions(
            needRebuild: true,
            color: Colors.transparent,
            downColor: const Color(0xFFEEEEEE),
            localImages: [controller.imgFavorite], //local images.
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Column(
      children: [
        Container(
          alignment: Alignment.centerLeft,
          margin: const EdgeInsets.only(bottom: 20),
          child: Text(
            '当前定位',
            style: StylesUtils.customTextStyle(
                fontSize: StylesUtils.fontSize13, color: ColorsUtils.color6666),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              constraints: const BoxConstraints.expand(width: 100, height: 30),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15),
                color: HexColor(ColorsUtils.colorF7f7),
              ),
              child: Text.rich(
                TextSpan(
                  children: [
                    WidgetSpan(
                        child: Icon(
                          CupertinoIcons.placemark_fill,
                          size: 15,
                          color: HexColor(ColorsUtils.colorFf64),
                        ),
                        alignment: PlaceholderAlignment.middle),
                    TextSpan(
                      text: ' 北海市',
                      style: StylesUtils.customTextStyle(
                        color: ColorsUtils.color0000,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Text(
              '重新定位',
              style: StylesUtils.customTextStyle(
                fontSize: StylesUtils.fontSize12,
                color: ColorsUtils.colorFf64,
              ),
            ),
          ],
        ),
        Container(
          alignment: Alignment.centerLeft,
          margin: const EdgeInsets.only(top: 20, bottom: 20),
          child: Text(
            '热门城市',
            style: StylesUtils.customTextStyle(
                fontSize: StylesUtils.fontSize13, color: ColorsUtils.color6666),
          ),
        ),
        Align(
          alignment: Alignment.centerLeft,
          child: Wrap(
            spacing: 8,
            runSpacing: 12,
            alignment: WrapAlignment.start,
            crossAxisAlignment: WrapCrossAlignment.center,
            children: [
              Container(
                constraints:
                    const BoxConstraints.expand(width: 100, height: 30),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: HexColor(ColorsUtils.colorF7f7),
                ),
                child: Text(
                  ' 北京',
                  style: StylesUtils.customTextStyle(
                    color: ColorsUtils.color0000,
                  ),
                ),
              ),
              Container(
                constraints:
                    const BoxConstraints.expand(width: 100, height: 30),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: HexColor(ColorsUtils.colorF7f7),
                ),
                child: Text(
                  ' 上海',
                  style: StylesUtils.customTextStyle(
                    color: ColorsUtils.color0000,
                  ),
                ),
              ),
              Container(
                constraints:
                    const BoxConstraints.expand(width: 100, height: 30),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: HexColor(ColorsUtils.colorF7f7),
                ),
                child: Text(
                  ' 广州',
                  style: StylesUtils.customTextStyle(
                    color: ColorsUtils.color0000,
                  ),
                ),
              ),
              Container(
                constraints:
                    const BoxConstraints.expand(width: 100, height: 30),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: HexColor(ColorsUtils.colorF7f7),
                ),
                child: Text(
                  ' 深圳',
                  style: StylesUtils.customTextStyle(
                    color: ColorsUtils.color0000,
                  ),
                ),
              ),
              Container(
                constraints:
                    const BoxConstraints.expand(width: 100, height: 30),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  color: HexColor(ColorsUtils.colorF7f7),
                ),
                child: Text(
                  ' 杭州',
                  style: StylesUtils.customTextStyle(
                    color: ColorsUtils.color0000,
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    ).paddingOnly(left: 15, top: 20, right: 15, bottom: 15);
  }

  void showSnackBar(BuildContext context, String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(msg),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  Widget getSusItem(BuildContext context, String tag, {double susHeight = 40}) {
    if (tag == '★') {
      tag = '★ 热门城市';
    }
    return Container(
      height: susHeight,
      width: MediaQuery.of(context).size.width,
      padding: const EdgeInsets.only(left: 15.0),
      color: const Color(0xFFF3F4F5),
      alignment: Alignment.centerLeft,
      child: Text(
        tag,
        softWrap: false,
        style: const TextStyle(
          fontSize: 14.0,
          color: Color(0xFF666666),
        ),
      ),
    );
  }

  Widget getListItem(BuildContext context, CityModel model,
      {double susHeight = 40}) {
    return ListTile(
      title: Text(model.name),
      onTap: () {
        showSnackBar(context, 'onItemClick : ${model.name}');
      },
    );
  }
}
